
const CHANNELS = 1;
const RATE = 44100;
const SAMPLESIZE = 16;
const CHUNK = 512;
const ws = new WebSocket('wss://' + window.location.hostname + ':' + window.location.port + '/audio_ws');
let audioContext;
let audioWorkletNode;
async function initAudio() {
    audioContext = new AudioContext();
    await audioContext.audioWorklet.addModule('processor.js');
    audioWorkletNode = new AudioWorkletNode(audioContext, 'audio-worklet-processor');
    audioWorkletNode.connect(audioContext.destination);
}

ws.binaryType = 'arraybuffer'; // 确保接收二进制数据
let audioContext_listen;
let audioSource_listen;
let stream_listen;
let processorNode;
send_flag = false;

let index_now = 0;
let audio_listen_buffer


async function startRecording() {
    if(send_flag){
        return;
    }
    index_now = 0;
    switch (SAMPLESIZE) {
        case 8:
            audio_listen_buffer = new Int8Array(CHUNK);
            break;
        case 16:
            audio_listen_buffer = new Int16Array(CHUNK);
            break;
        case 24:
            audio_listen_buffer = new Int32Array(CHUNK);
            break;
        case 32:
            audio_listen_buffer = new Int32Array(CHUNK);
            break;
    }
    send_flag = true;
    stream_listen = await navigator.mediaDevices.getUserMedia({
        audio: {
            sampleRate: RATE,
            channelCount: CHANNELS,
            sampleSize: SAMPLESIZE
        }
    });
    audioContext_listen = new AudioContext();
    audioSource_listen = audioContext_listen.createMediaStreamSource(stream_listen);
    await audioContext_listen.audioWorklet.addModule('/static/js/recorder-worklet.js');
    processorNode = new AudioWorkletNode(audioContext_listen, 'recorder-worklet');
    audioSource_listen.connect(processorNode);
    // audioSource_listen.connect(processorNode).connect(audioContext_listen.destination);
    audioSource_listen.connect(processorNode);
    processorNode.port.onmessage = function (event) {
        if (send_flag) {
            n = event.data.length;
            for (let i = 0; i < n; i++) {
                audio_listen_buffer[index_now] = event.data[i];
                index_now++;
            }
            if (index_now >= CHUNK) {
                index_now = 0;
                ws.send(audio_listen_buffer.buffer);
            }
        }
    }
}
document.getElementById('listenBtn').addEventListener('click', startRecording);
function stopRecording() {
    send_flag = false;
    stream_listen.getTracks().forEach(track => track.stop());
    // 3. 断开节点连接
    if (processorNode) {
        processorNode.disconnect();
        processorNode = null;
    }
    // 2. 关闭音频上下文
    if (audioContext_listen) {
        audioContext_listen.close();
        audioContext_listen = null;
    }
    // 4. 释放资源引用
    audioSource_listen = null;
}
document.getElementById('stop_listen_Button').addEventListener('click', function () {
    stopRecording();
});

let audioContext_shou;
let sourceNode_shou;
let websocket_shou;
let isPlaying = false;
const bufferQueue = [];
const CHUNK_SIZE_shou = 1024; // 与ESP32发送的CHUNK大小一致
let scriptNode_shou; // 在这里声明 scriptNode

document.getElementById('playButton').addEventListener('click', async function() {
    if (!isPlaying) {
        // 初始化音频上下文
        audioContext_shou = new (window.AudioContext || window.webkitAudioContext)();
        
        // 创建音频处理节点
        scriptNode_shou = audioContext_shou.createScriptProcessor(CHUNK_SIZE_shou, 1, 1); // 在这里初始化 scriptNode
        
        // 连接WebSocket
        websocket_shou = new WebSocket('wss://' + window.location.hostname + ':' + window.location.port + '/audio_ws');
        websocket_shou.binaryType = 'arraybuffer';

        // 处理接收到的音频数据
        websocket_shou.onmessage = function(event) {
            const rawData = new Int16Array(event.data);
            const float32Data = new Float32Array(rawData.length);
            
            // 转换为Web Audio API需要的格式
            for (let i = 0; i < rawData.length; i++) {
                float32Data[i] = rawData[i] *3/ 32768.0;
            }
            
            bufferQueue.push(...float32Data);
        };

        // 音频处理回调
        scriptNode_shou.onaudioprocess = (audioEvent) => {
            const outputBuffer = audioEvent.outputBuffer;
            const outputData = outputBuffer.getChannelData(0);
            const neededSamples = outputData.length;
            
            if (bufferQueue.length >= neededSamples) {
                outputData.set(bufferQueue.splice(0, neededSamples));
            } else {
                outputData.fill(0); // 数据不足时静音
            }
        };

        // 连接音频节点
        scriptNode_shou.connect(audioContext_shou.destination);
        isPlaying = true;
        this.textContent = '停止播放';
    } else {
        // 检查 scriptNode 是否已定义
        if (scriptNode_shou) {
            scriptNode_shou.disconnect();
        }
        // 关闭所有资源
        if (audioContext_shou) {
            audioContext_shou.close();
        }
        if (websocket_shou) {
            websocket_shou.close();
        }
        isPlaying = false;
        this.textContent = '开始播放';
        bufferQueue.length = 0;
    }
});